<template>
  <div>
    <el-table
      :data="state.tableData"
      class="customer-table"
      max-height="300"
      v-loading="state.loading"
      header-cell-class-name="eltablebg"
      header-row-class-name="radius-8"
      style="width: 100%"
    >
      <el-table-column
        prop
        :label="$t('exchange.lever')"
        label-class-name="left-radius-8"
      >
        <template #default="r">
          <span>
            {{
              r.row.currency_name +
                "/" +
                r.row.legal_name +
                " x" +
                r.row.lever_multiple
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="lever_open_price"
        :label="$t('exchange.openingPrice')"
      >
        <template #default="r">
          {{ $currency(r.row.lever_open_price) }}
        </template>
      </el-table-column>
      <el-table-column prop="lever_earnest_money" :label="$t('exchange.margin')"
        ><template #default="r">
          {{ r.row.lever_earnest_money }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="lever_hand"
        width="130"
        :label="$t('exchange.lot')"
      ></el-table-column>
      <el-table-column align="center" prop :label="$t('deal.stoploss')">
        <template #default="r">
          <span>{{
            (r.row.stop_win_price ? $currency(r.row.stop_win_price) : "--") +
              "/" +
              (r.row.stop_lose_price ? $currency(r.row.stop_lose_price) : "--")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="lever_type"
        :label="$t('exchange.type')"
      >
        <template #default="r">
          <span :class="r.row.lever_type === 1 ? 'text-green' : 'text-red'">
            {{
              r.row.lever_type === 1
                ? $t("exchange.doMore")
                : $t("exchange.short")
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="lever_open_time"
        :label="$t('lever.opentime')"
      >
        <template #default="r">
          <span>{{ getTimeZoneDate(r.row.lever_open_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="trade_fee"
        :label="$t('assets.handlingFee')"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="lever_overnight_fee"
        :label="$t('exchange.overnightFee')"
      ></el-table-column>
      <el-table-column
        align="center"
        prop
        :label="$t('exchange.profitAndLoss')"
      >
        <template #default="r">
          <span
            :class="
              counprofit(
                r.row.lever_open_price,
                r.row.lever_hand,
                r.row.lever_hand_number,
                r.row.lever_type,
                r.row.price_accuracy
              ) < 0
                ? 'text-red'
                : 'text-green'
            "
          >
            {{
              $currency(
                counprofit(
                  r.row.lever_open_price,
                  r.row.lever_hand,
                  r.row.lever_hand_number,
                  r.row.lever_type,
                  r.row.price_accuracy
                )
              )
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop :label="$t('exchange.profitAndLossRate')">
        <template #default="r">
          <span
            :class="
              counprofitRate(
                r.row.lever_open_price,
                r.row.lever_hand,
                r.row.lever_hand_number,
                r.row.lever_type,
                r.row.lever_overnight_fee,
                r.row.lever_earnest_money
              ) < 0
                ? 'text-red'
                : 'text-green'
            "
          >
            {{
              counprofitRate(
                r.row.lever_open_price,
                r.row.lever_hand,
                r.row.lever_hand_number,
                r.row.lever_type,
                r.row.lever_overnight_fee,
                r.row.lever_earnest_money
              ) > 0
                ? "+"
                : ""
            }}
            {{
              $currency(
                decimalDigitsInputFilter(
                  counprofitRate(
                    r.row.lever_open_price,
                    r.row.lever_hand,
                    r.row.lever_hand_number,
                    r.row.lever_type,
                    r.row.lever_overnight_fee,
                    r.row.lever_earnest_money
                  ),
                  2
                )
              )
            }}
            %
          </span>
        </template>
      </el-table-column>
      <el-table-column
        align="right"
        prop
        :label="$t('assets.operate')"
        label-class-name="right-radius-8"
      >
        <template #default="r">
          <div>
            <el-button type="text" class="free-box" @click="winloseStop(r.row)">
              {{ $t("exchange.stopLoss") }}
            </el-button>
            <el-button type="text" @click="close(r.row.id)">
              {{ $t("exchange.liquidation") }}
            </el-button>
          </div>
        </template>
      </el-table-column>
      <template #empty>
        <div>
          <Norecord :useDark="true" />
          <!-- <div class="quotet3 text-12 mb-60 l-10">暂无数据</div> -->
        </div>
      </template>
    </el-table>
    <!-- 平仓 -->
    <Messagebox
      :dialog="state.dialog"
      :text="$t('lever.close')"
      :type="3"
      @onconfirm="confirm"
      @oncancer="state.dialog = false"
    />
    <!-- 监听table滚动条触底 -->
    <Tablescroll @scroll="tableScroll" />
  </div>
</template>

<script>
import Norecord from "@/components/noRecord/NoRecord.vue";
import { onMounted, reactive, watch, computed } from "vue";
import { leverPage, closeOrderLever } from "@/api/currency";
import { democloseOrderLever, demoleverPage } from "@/api/demo";
import UseSystemSetting from "@/commonapi/useSystemSetting";
import Messagebox from "@/components/messageBox/index.vue";
import { ElMessage } from "element-plus";
import Tablescroll from "@/components/tablescroll/index.vue";
import { decimalDigitsInputFilter } from "@/utils/common";
import { useStore } from "vuex";
import { getTimeZoneDate } from "@/utils/times.js";

export default {
  name: "Contract",
  components: { Norecord, Messagebox, Tablescroll },
  props: { checked: Boolean, tradingid: Number, nowPrice: Number },
  emits: ["winlose", "curenttotal"],
  setup(props, { emit }) {
    const $store = useStore();
    const state = reactive({
      listParam: {
        page: 0,
        limit: 10,
        lever_status: 2,
      },
      loading: false,
      tableData: [],
      dialog: false,
      orderId: "", //平仓id
      total: 0,
    });
    /**
     * methods
     */
    onMounted(() => {
      if ($store.state.user.token) {
        getList();
      }
    });
    // eslint-disable-next-line no-unused-vars
    watch(
      () => [props.tradingid, $store.state.user.token],
      ([val, oldval], [newtoken, oldtoken]) => {
        console.log(val, oldval, oldtoken);
        if (newtoken == val) {
          state.tableData = [];
          emit("curenttotal", 0);
          return;
        } else {
          if (val !== oldval) {
            state.listParam.page = 0;
            getList();
          }
        }
      }
    );
    watch(
      () => props.checked,
      () => {
        state.listParam.page = 0;
        getList();
      }
    );
    const getorderType = computed(() => {
      return $store.state.exchange.leverOrder_type;
    });
    // 获取开关状态
    const { virtual_wallet } = UseSystemSetting();
    watch(
      () => [getorderType.value, virtual_wallet.value],
      () => {
        if ($store.state.user?.token) {
          state.listParam.page = 0;
          getList();
        }
      }
    );
    const getList = () => {
      const param = { ...state.listParam };
      // 判断是否只显示当前币
      // if (props.checked) {

      // }
      param.currency_match_id = props.tradingid;
      state.loading = true;
      let setFun = virtual_wallet.value ? demoleverPage : leverPage;
      setFun(param)
        .then((res) => {
          state.loading = false;
          if (state.listParam.page === 0) {
            state.tableData = res.data.items;
            emit("curenttotal", res.data.total);
          } else {
            state.tableData = state.tableData.concat(res.data.items);
          }
          state.total = res.data.total;
        })
        .catch(() => {
          state.loading = false;
        });
    };
    // 止盈止损
    const winloseStop = (item) => {
      emit("winlose", item);
    };
    // 平仓
    const close = (id) => {
      state.orderId = id;
      state.dialog = true;
    };
    const confirm = () => {
      let setFun = virtual_wallet.value ? democloseOrderLever : closeOrderLever;
      setFun({ id: state.orderId }).then((res) => {
        if (res.code === 200) {
          state.dialog = false;
          ElMessage({
            type: "success",
            message: res.message,
          });
          state.listParam.page = 0;
          getList();
        }
      });
    };
    // table滚动条触底
    const tableScroll = () => {
      if (state.total > state.tableData.length) {
        state.listParam.page = state.listParam.page + 1;
        getList();
      }
    };
    // 计算盈亏
    // 1买多  盈亏 = (当前价-开仓价)*手数*每手个数
    // 2卖空  盈亏 = (开仓价-当前价)*手数*每手个数
    const counprofit = (price, hand, numhand, type, price_accuracy) => {
      let profit = 0;
      if (type === 1) {
        profit = (props.nowPrice - price) * hand * numhand;
      } else {
        profit = (price - props.nowPrice) * hand * numhand;
      }
      return decimalDigitsInputFilter(profit, price_accuracy);
    };
    const counprofitRate = (price, hand, numhand, type, overnight, earnest) => {
      let rate = 0;
      let profit = counprofit(price, hand, numhand, type);
      rate = ((profit - overnight) / earnest) * 100;
      return rate;
    };
    return {
      state,
      getList,
      winloseStop,
      close,
      confirm,
      tableScroll,
      counprofit,
      getTimeZoneDate,
      counprofitRate,
      decimalDigitsInputFilter,
    };
  },
};
</script>

<style scoped lang="less"></style>
